package com.lucian.ge.user.controller;

import com.lucian.ge.user.mapper.UserMapper;
import com.lucian.ge.comman.model.ResultMap;
import com.lucian.ge.user.model.User;
import com.lucian.ge.util.JWTUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by Lucicol on 2019/5/17.
 */
@Api(value = "ChangePasswordController", description = "用户修改密码")
@RestController
public class ChangePasswordController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final UserMapper userMapper;
    private final ResultMap resultMap;

    @Autowired
    public ChangePasswordController(UserMapper userMapper, ResultMap resultMap) {
        this.userMapper = userMapper;
        this.resultMap = resultMap;
    }

    @ApiOperation(value="用户修改密码", notes="手机号/短信验证码/密码")

    @PostMapping("/changepassword")
    @ResponseBody
    public ResultMap changepassword(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) @Valid User user , BindingResult result) {

        //      参数校验
        if (result.hasErrors()) {
            return resultMap.fail().code(401).message(result.getFieldError().getDefaultMessage());
        }

        //        短信证码过期
        if (redisTemplate.opsForValue().get(user.getUsername()+"sms") == null) {
            return resultMap.fail().code(401).message("短信验证码过期请刷新");
        }

        //        短信验证码校验
        if (!user.getSmscode().equals(redisTemplate.opsForValue().get(user.getUsername()+"sms"))) {
            return resultMap.fail().code(401).message("短信验证码错误");
        }

        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes()) + DigestUtils.md5DigestAsHex(user.getUsername().getBytes());

        userMapper.updatePassword(user.getUsername(), password);

        return resultMap.success().code(200).message("修改密码成功,请登录");
    }
}
